package com.paradogs.framework.master.controller;

import com.paradogs.framework.common.pojo.gc.GCAllocGateway;
import com.paradogs.framework.core.annoations.request.PRController;
import com.paradogs.framework.core.annoations.request.PRMsgMapping;
import com.paradogs.framework.core.msg.GCAck;
import com.paradogs.framework.core.msg.PRMsgContextHolder;
import com.paradogs.framework.core.netty.PRConnHolder;
import com.paradogs.framework.core.netty.server.PRConnection;
import com.paradogs.framework.core.netty.server.ServerProperties;
import com.paradogs.framework.core.strategy.GateLoadBalancerStrategy;
import com.paradogs.framework.core.utils.IPUtils;
import com.paradogs.framework.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author: yumi
 * @date: 2023/8/24  17:45
 * @Description: TODO
 */
@Slf4j
@PRController
@PRMsgMapping("_master")
public class MasterController {

    @Autowired
    private GateLoadBalancerStrategy strategy;

    /**
     * 服务器注册和初始化
     * @param properties
     */
    @PRMsgMapping("init")
    public void init(ServerProperties properties) {
        // 初始化连接的服务器信息（建立连接后，服务器主动发送自己的信息）
        PRConnHolder.initConn(PRMsgContextHolder.getChannel(), properties);
        log.info("Server connection init success: {}|{}, {}", properties.getType(), properties.getKey(), IPUtils.getAddr(PRMsgContextHolder.getChannel()));
    }

    /**
     * 玩家登录成功后，登录服申请一个网关供玩家连接
     * @return
     */
    @PRMsgMapping("allocGate")
    public GCAllocGateway allocGate() {
        List<PRConnection> gates = PRConnHolder.getConns("gate");
        PRConnection conn = strategy.choose(gates);
        if (conn == null) {
            GCAck.fail();
        }

        InetSocketAddress addr = IPUtils.getAddr(conn.getChannel());
        return new GCAllocGateway(addr.getHostString(), conn.getProperties().getPort());
    }

}
